<!--
 * @Descripttion: 
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-07-21 10:45:02
 * @LastEditTime: 2022-11-14 16:07:38
-->
<template>
  <div class="subscription-list">
    <dt-search ref="search" :labelWidth="80" :xl="4" @reset="resetFun">
    </dt-search>
    <dt-grid ref="table" page :onFetch="onFetch" :select="{change:selectionChange}"
      :emptyText="emptyText">
      <div class="flex btn-content" slot="btn">
        <Button type="primary" @click="addOrder()" style="margin-right:8px;"
          @onCheck="checkOrderFun">添加订单</Button>
        <Button type="primary" @click="delOrder()" style="margin-right:8px;"
          :disabled="!selectionRows.length">删除订单</Button>
        <Button type="primary" @click="emptyOrder()" style="margin-right:8px;"
          :disabled="!list.length">清空列表</Button>
        <Button type="primary" @click="batchOrder()" style="margin-right:8px;"
          :disabled="!list.length">批量修改</Button>
        <Button type="primary" @click="submitExamine()" style="margin-right:8px;"
          :disabled="existenceUSave">提交审核</Button>
        <Button type="primary" @click="saveFun({})" style="margin-right:8px;"
          :disabled="!list.length">暂存</Button>
        <Button type="primary" @click="exportFun()" style="margin-right:8px;"
          :disabled="!list.length">导出Excel</Button>
      </div>
    </dt-grid>
    <!--添加订单-->
    <check-order ref="checkOrder" @onSearch="searchFun"></check-order>
    <!--批量修改-->
    <batch-page ref="batchPage" @onSearch="searchFun"></batch-page>
    <!--提交审核-->
    <examine-page ref="examinePage" @onSearch="searchFun"></examine-page>
    <!--客户详情-->
    <Modal v-model="detailsFlag" title="客户详情" width="80%" :styles="{top:'5%'}"
      :footer-hide="true">
      <detail-page v-if="detailsFlag" :detailsParams="detailsParams"></detail-page>
    </Modal>
  </div>
</template>
<script>
  import detailPage from '../../../allCustomersManagement/details.vue'
  import batchPage from '../components/batchPage.vue'
  import examinePage from './examinePage.vue'
  import adjustSubColumn from './subColumn'
  import adjustConColumn from './conColumn'
  import searchOpt from './search'
  import checkOrder from './checkOrder.vue'
  import adjustMgr from '@/biz/sales/adjustOrder'
  import dt from '@dt/dt'
  export default {
    props: ['isSub'],
    watch: {
      list: {
        handler(n) {
          this.existenceUSave = this.list.filter(item => item.editFlag).length ? true : false
        },
        deep: true
      }
    },
    data() {
      return {
        existenceUSave: false,
        detailsFlag: false,
        detailsParams: {},
        searchInfo: {
          housesId: dt.buildInfo().housesId,
          productId: '', //产品
          buildingId: '',
          unitId: ''
        },
        emptyText: '暂无数据，您可点击列表上方的“添加订单”按钮，添加需要调整面积或总价的订单',
        filterParams: {},
        selectionRows: [],
        list: [],
        total: 0,
        saveOperate: false
      }
    },
    components: {
      detailPage,
      checkOrder,
      batchPage,
      examinePage
    },
    created() {},
    mounted() {
      if (this.isSub) {
        this.$refs.table.init(this, new adjustSubColumn(this))
      } else {
        this.$refs.table.init(this, new adjustConColumn(this))
      }
      this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
        .searchInfo)
      this.$refs.table.fetch()
    },
    methods: {
      resetFun() {
        this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
          .searchInfo)
      },
      selectionChange(selection) {
        this.selectionRows = selection
      },
      searchFun() {
        this.$refs.table.fetch()
      },
      operateSave() {
        let filterArr = this.list.filter(item => item.editFlag)
        return filterArr.length
      },
      onFetch(data) {
        if (this.existenceUSave && !this.saveOperate) {
          this.$Message.info(`列表中有部分订单未保存，请重新修改订单`)
        }

        let params = {
          ...data,
          adjustmentId: this.$route.query.adjustmentId
        }
        this.filterParams = { ...params }

        return adjustMgr.getAdjustOrderList(params).then(res => {
          this.selectionRows = []
          this.list = res.list
          this.total = res.total
          if (this.saveOperate) {
            this.saveOperate = false
          }
          return res
        }).catch(err => {})
      },
      // 客户姓名链接到客户资料
      onLinkUser(row) {
        if (row.customerName == '-') {
          return false
        }
        this.detailsFlag = true
        this.detailsParams = {
          customerId: row.customerId,
          userCustomerId: row.userCustomerId,
          buildingId: dt.buildInfo().housesId,
          userId: dt.userInfo().userId,
          cityCode: dt.buildInfo().cityId,
        }
      },
      addOrder() {
        this.$refs.checkOrder.show(this.isSub)
      },
      checkOrderFun() {
        this.$refs.table.fetch()
      },
      delOrder() {
        let params = {
          adjustmentId: this.$route.query.adjustmentId,
          ids: this.selectionRows.map(item => { return item.id })
        }
        this.$Modal.confirm({
          title: '是否确认删除所选订单？',
          onOk: () => {
            adjustMgr.deleteAdjustmentOrderFun(params).then(res => {
              this.$Message.success('删除成功')
              this.$refs.table.fetch()
            }).catch(err => {})
          }
        })
      },
      emptyOrder() {
        let params = {
          adjustmentId: this.$route.query.adjustmentId
        }
        this.$Modal.confirm({
          title: '是否确认清空所选订单？',
          onOk: () => {
            adjustMgr.emptyAdjustmentOrderFun(params).then(res => {
              this.$Message.success('操作成功')
              this.$refs.table.fetch()
            }).catch(err => {})
          }
        })
      },
      batchOrder() {
        this.$refs.batchPage.show()
      },
      submitExamine() {
        let titleText = ''
        let contentText = ''

        if (!this.list.length) {
          this.$Message.error(`列表中暂无${this.isSub?'认购':'签约'}单，请点击列表上方的“添加订单”按钮，添加需要调整面积或总价的订单`)
          return false
        }

        let params = {
          adjustmentId: this.$route.query.adjustmentId
        }

        adjustMgr.getUnAdjustmentNum(params).then(res => {
          if (this.isSub) {
            titleText = '认购调整申请确认'
            contentText =
              `您提交的认购单中有${res.unAdjustmentNum}个认购单的面积及总价未发生变更，系统将自动从列表中移除。请确认，是否继续提交调整申请？`
          } else {
            titleText = '签约调整申请确认'
            contentText =
              `您提交的签约单中有${res.unAdjustmentNum}个签约单的面积及总价未发生变更，系统将自动从列表中移除。请确认，是否继续提交调整申请？`
          }
          if (res.unAdjustmentNum == this.total) {
            this.$Message.error(`列表中所有订单的面积或总价均未变更，请再调整后再提交审核`)
            return false
          }
          if (res.unAdjustmentNum) {
            this.$Modal.confirm({
              title: titleText,
              content: contentText,
              okText: '继续提交',
              onOk: () => {
                this.$refs.examinePage.show(this.isSub, res.adjustmentId)
              }
            })
          } else {
            this.$refs.examinePage.show(this.isSub, res.adjustmentId)
          }
        }).catch(err => {})
      },
      saveFun(row) {
        // 校验不能小于0  且保留两位小数
        let reg = /^[\d,-]?\d+(\.\d{1,2}){0,1}$/

        let orderListsResolve = (!Object.keys(row).length) ? this.list : [row]

        let USaveList = orderListsResolve.filter(item => { return item.editFlag })

        if (!USaveList.length) {
          this.$Message.error(`没有未保存的${this.isSub?"认购单":"签约单"}`)
          return false
        }
        // 批量暂存 保存
        try {
          orderListsResolve.forEach(item => {
            if (item.afterAdjustArea < 0) {
              this.$Message.error('请检查，调整后面积不能小于0')
              throw Error();
            }
            if (item.afterAdjustPrice < 0) {
              this.$Message.error('请检查，调整后总价不能小于0')
              throw Error();
            }

            if (item.afterAdjustArea && !reg.test(item.afterAdjustArea)) {
              this.$Message.error('请检查，调整后面积保留两位小数')
              throw Error();
            }
            if (item.afterAdjustPrice && !reg.test(item.afterAdjustPrice)) {
              this.$Message.error('请检查，调整后总价保留两位小数')
              throw Error();
            }

            if ((item.afterAdjustArea === '' || item.afterAdjustArea === null) && (item
                .afterAdjustPrice === '' || item
                .afterAdjustPrice === null)) {
              this.$Message.error('请检查，调整后面积和总价均为空')
              throw Error();
            }
          })
        } catch (e) {
          return false
        }

        let params = {
          adjustmentId: this.$route.query.adjustmentId,
          orderLists: orderListsResolve.map(item => {
            return {
              adjustmentDetailId: item.id,
              afterAdjustArea: item.afterAdjustArea,
              afterAdjustPrice: item.afterAdjustPrice,
              currentAdjustArea: item.currentAdjustArea,
              currentAdjustPrice: item.currentAdjustPrice,
              orderId: item.orderId
            }
          })
        }
        adjustMgr.auditAdjustmentOrderFun(params).then(res => {
          this.$Message.success('保存成功')
          this.saveOperate = true
          this.$refs.table.fetch()
        }).catch(err => {})

      },
      // 修改订单
      editFun(row) {
        let USaveList = this.list.filter(item => { return item.editFlag })

        if (USaveList.length) {
          this.$Message.error(`存在未保存的${this.isSub?"认购单":"签约单"}，请先保存`)
          return false
        }
        row.editFlag = true
      },
      calculationFun(row) {
        // 计算
        row.areaDV = (row.afterAdjustArea - row.currentAdjustArea).toFixed(2)
        row.priceDV = (row.afterAdjustPrice - row.currentAdjustPrice).toFixed(2)
      },
      // 取消
      cancelFun(row) {
        // 数据重置  重新计算面积总价差
        row.editFlag = false
        row.afterAdjustArea = row.afterAdjustAreaCopy
        row.afterAdjustPrice = row.afterAdjustPriceCopy
        row.priceDV = row.priceDVCopy
        row.areaDV = row.areaDVCopy
      },
      // 导出
      exportFun() {
        let params = { ...this.filterParams }
        params.adjustId = params.adjustmentId
        adjustMgr
          .exportAdjustDetailFun(params)
          .then((res) => {})
          .catch((err) => {})
      }
    },
  }
</script>
<style lang="scss" scoped>
  .subscription-list {
    padding: 20px;

    .empty-text {
      text-align: center;
      font-size: 18px;
      color: #999;
      margin: 300px 0;
    }
  }
</style>